import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, DatePicker, Badge, Divider, Select } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './DevFix.less';
import OperationForm from '../../components/OperationForm';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['待处理', '已指派', '已处理'];
const statusMap = ['default', 'processing', 'success', 'error'];
const alarmStatus = ['默认', '播放内容自动审核报警', '车辆求助报警'];

@connect(({ devalarm }) => ({
    devalarm,
}))
@Form.create()
export default class DevAlarm extends PureComponent {
    state = {
        selectedRows: [],
        record: {},
        modalVisible: false,
        opType: 'devbind',
    };

    componentDidMount() {
        const payload = {};
        const { dispatch } = this.props;
        dispatch({
            type: 'devalarm/fetch',
            payload,
        });
    }

    onbind = record => {
        this.setState({ record });
        this.handleModalVisible(true, this.state.opType);
    };
    handleModalVisible = (flag, opType) => {
        // console.log('modal visible', flag, opType);
        this.setState({
            modalVisible: !!flag,
            opType,
        });
    };

    getFromValue = () => {
        const { form } = this.props;
        let postvalue = {};
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const { entries } = Object;

            for (const [key, value] of entries(fieldsValue)) {
                if (value !== null && value !== undefined) {
                    postvalue[key] = value;
                }
            }
            //console.log('postvalue', postvalue);
            if (postvalue.date && postvalue.date.length > 0) {
                const startSubDate = postvalue.date[0].format('YYYY-MM-DD');
                const endSubDate = postvalue.date[1].format('YYYY-MM-DD');
                postvalue = {
                    ...postvalue,
                    startSubDate,
                    endSubDate,
                };
                delete postvalue.date;
            }
        });
        return postvalue;
    };
    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = { ...obj };
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});
        const postvalue = this.getFromValue();
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...postvalue,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'devalarm/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        dispatch({
            type: 'devalarm/fetch',
            payload: {},
        });
    };

    handleSearch = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const postvalue = this.getFromValue();
        dispatch({
            type: 'devalarm/fetch',
            payload: postvalue,
        });
    };

    downloadFile = () => {
        //  const fileName = '';

        const postvalue = this.getFromValue();
        this.props.dispatch({
            // 发送请求
            type: 'devalarm/export',
            payload: postvalue,
            callback: response => {
                const aLink = document.createElement('a'); // 创建a链接
                aLink.style.display = 'none';
                aLink.href = response;
                //    aLink.download = fileName;
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink); // 点击完成后记得删除创建的链接
            },
        });
    };
    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={6} sm={24}>
                        <FormItem>
                            {getFieldDecorator('date')(
                                <RangePicker
                                    showTime={{ format: 'HH:mm' }}
                                    format="YYYY-MM-DD HH:mm"
                                    placeholder={['开始时间', '结束时间']}
                                    style={{ width: '100%' }}
                                />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={3} sm={24}>
                        <FormItem>
                            {getFieldDecorator('devUuid', {
                                rules: [{ required: false, message: '请输入设备ID!' }],
                            })(<Input placeholder="设备ID" />)}
                        </FormItem>
                    </Col>
                    <Col md={3} sm={24}>
                        <FormItem>
                            {getFieldDecorator('vehLicplateNo', {
                                rules: [{ required: false, message: '请输入车牌号!' }],
                            })(<Input placeholder="车牌号" />)}
                        </FormItem>
                    </Col>

                    <Col md={3} sm={24}>
                        <FormItem>
                            {getFieldDecorator('alarmType', {
                                rules: [{ required: false, message: '请输入报警类型!' }],
                            })(<Select style={{ width: 200 }} allowClear placeholder="报警类型">
                                <Select.Option value={0}>播放内容自动审核报警</Select.Option>
                                <Select.Option value={1}>车辆求助报警</Select.Option>
                            </Select>)}
                        </FormItem>
                    </Col>
                    <Col md={3} sm={24}>
                        <FormItem>
                            {getFieldDecorator('procStatus', {
                                rules: [{ required: false, message: '请输入处理状态!' }],
                            })(<Select style={{ width: 200 }} allowClear placeholder="处理状态">
                                <Select.Option value={0}>待处理</Select.Option>
                                <Select.Option value={1}>已指派</Select.Option>
                                <Select.Option value={2}>已处理</Select.Option>
                            </Select>)}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
                            查询
            </Button>

                        {/* <Button type="primary" style={{ marginRight: 10 }} onClick={() => this.downloadFile()}>
                            导出
            </Button> */}

                    </Col>
                </Row>
            </Form>
        );
    }

    render() {
        // //console.log('task', this.props.task);
        const { devalarm, loading } = this.props;
        const { selectedRows } = this.state;
        const columns = [
            {
                title: '报警时间',
                dataIndex: 'createTime',
            },
            {
                title: '设备ID',
                dataIndex: 'devUuid',
            },

            {
                title: '车牌号',
                dataIndex: 'vehLicplateNo',
            },
            {
                title: '报警类型',
                dataIndex: 'alarmType',
            },

            {
                title: '问题描述',
                dataIndex: 'alarmDescr',
            },
            {
                title: '处理状态',
                dataIndex: 'procStatus',

            },

            {
                title: '操作',
                render: (text, record) => (
                    <Fragment>
                        <Link
                            to={{
                                pathname: `/devmaintain/alarmDet/${record.alarmId}`,
                                record,
                            }}
                        >
                            详情
            </Link>
                        <Divider type="vertical" />
                        <a href={record.alarmFileUrl}>下载</a>

                    </Fragment>
                ),
            },
        ];

        return (
            <PageHeaderLayout title="设备报警">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
                        <StandardTable
                            rowKey="setId"
                            selectedRows={selectedRows}
                            loading={loading}
                            data={devalarm}
                            columns={columns}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>

            </PageHeaderLayout>
        );
    }
}
